<?php

require_once 'ActionFramework/start.php';
require_once 'actions/login_abstract.cls.php';

class LoginAction extends AbstractLoginAction {
	
	const INPUT_CHALLENGE_ID = "challenge_id";
	const INPUT_EMAIL = "email";
	const INPUT_PASSWORD = "password";
	
	public function __construct() {
		parent::__construct();
		$this->add_input(new EmailInput(LoginAction::INPUT_EMAIL, 'Email'));
		$this->add_input(new Input(LoginAction::INPUT_PASSWORD, 'Password'));
		$this->add_input(LoginAction::INPUT_CHALLENGE_ID);
	}
	
	public function verify_credentials(Array $request) {
		
		$email = $request[LoginAction::INPUT_EMAIL];
		// Password is hashed, with the system salt and the challenge
		$user_password_cocktail = $request[LoginAction::INPUT_PASSWORD];
		$challenge_id = $request[LoginAction::INPUT_CHALLENGE_ID]; 
		
		global $DB;
		$challenge = $DB->get_challenge($challenge_id);
		if ($challenge !== null) {
			$user = $DB->get_user_by_email($email);
			if ($user !== null) {
				// user password is already hashed with the system salt
				$server_password_cocktail = sha1($user->password.$challenge);
				if ($server_password_cocktail === $user_password_cocktail) {
					return $user;
				}	
			}
		}
		
		// Login failed
		return null;
		
	}
	
	public function redirect_invalid_credentials() {
		$start_view = r(new StartAction())->trigger(array());
		$start_view->add_message("
			The login failed: the user and password combination
			is not known, or the login window expired. Perhaps you want to 
  			<a href='javascript:login_or_signup(\"signup\")'>register</a> or
  			<a href='javascript:login_or_signup(\"login\")'>try again</a>?
		");
		return $start_view;
	}
	
}

?>
